import fs from 'fs'
import path from 'path'
import {dialog} from 'electron'
export const saveFile = async (fileName:string,data:any)=>{
  return new Promise((res,rej)=>{
    let rpath = path.join(__dirname,fileName)
    fs.writeFile(rpath,data,(err)=>{
      if(err){
        rej(err)
      }else{
        res(true)
      }
    })
  })
}

export const readFile = async (p:string)=>{

  return new Promise((res,rej)=>{
    let rPath = path.join(__dirname,p)
    fs.readFile(rPath,(err,data)=>{
      if(err){
        rej(err)
      }else{
        res(data)
      }
    })
  })
}
/**
 * 读取文件
 */
export const openFile = async ()=>{
  return new Promise((res,rej)=>{
    dialog.showOpenDialog({
      properties: ['openFile'],
      filters: [
        { name: 'Text Files', extensions: ['txt','md'] },
        // 其他文件类型...
      ],
    }).then(async (result)=>{
      if (result.filePaths.length > 0) {
        // result.filePaths[0] 就是用户选择的文件路径
        try{
          let fileData = await readFileData(result.filePaths[0])
          res(fileData)
        }catch (e) {
          rej(e);
        }
      }else{
        rej('no path')
      }
    })
  })
}


const readFileData = async (path)=>{
  return new Promise((res,rej)=>{
    fs.readFile(path,'utf8',(err,data)=>{
      if(err){
        rej(err)
      }else{
        res(data);
      }
    })
  })
}

/**
 * 读取文件夹
 */
export const readFileDic =async ()=>{
  return new Promise((res,rej)=>{
    //调用系统文件选择框
    dialog.showOpenDialog({
      properties: ['openDirectory']
    }).then(async (result) => {
      if (result.filePaths.length > 0) {
        const folderPath = result.filePaths[0];
        try{
          let datas:any = await reddir(folderPath)


          res(datas)
        }catch (e:any) {
          rej('read files error:',e)
        }
      }else{
        rej('no path')
      }
    });
  })
}

/**
 * 读取文件夹下的内容
 */
const reddir = async (directory)=>{
  return new Promise((res,rej)=>{
    fs.readdir(directory, (err, files) => {
      if (err) {
        console.error('读取文件时出错:', err);
        rej(err)
      }
      res(files)
    });
  })
}

